<?php

namespace App\Http\Controllers\Wechat\WechatServiceAccount;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\SimpleCart;
use Illuminate\Support\Facades\Auth;

class CartController extends Controller
{
    /**
     * 显示购物车页面
     */
    public function index(Request $request)
    {
        // 检查用户是否已登录
        if (!auth('wechat')->check()) {
            return redirect()->route('wechat.service.account.login');
        }

        // 获取当前用户的购物车商品
        $cartItems = SimpleCart::where('user_id', auth('wechat')->id())
            ->with('product')
            ->get();

        $totalPrice = 0;
        $cartData = [];

        foreach ($cartItems as $item) {
            if ($item->product) {
                $subtotal = $item->product->price * $item->quantity;
                $cartData[] = [
                    'id' => $item->id,
                    'product' => $item->product,
                    'quantity' => $item->quantity,
                    'subtotal' => $subtotal,
                ];
                $totalPrice += $subtotal;
            }
        }

        return view('wechat.service_account.cart', compact('cartData', 'totalPrice'));
    }

    /**
     * 添加商品到购物车
     */
    public function add(Request $request)
    {
        // 检查用户是否已登录
        if (!auth('wechat')->check()) {
            return response()->json([
                'success' => false,
                'message' => '请先登录'
            ], 401);
        }

        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
        ]);

        $productId = $request->input('product_id');
        $quantity = (int)$request->input('quantity');
        $userId = auth('wechat')->id();

        // 检查商品是否存在且有库存
        $product = Product::find($productId);
        if (!$product) {
            return response()->json([
                'success' => false,
                'message' => '商品不存在'
            ]);
        }

        if ($product->stock < $quantity) {
            return response()->json([
                'success' => false,
                'message' => '库存不足'
            ]);
        }

        // 检查购物车中是否已存在该商品
        $cartItem = SimpleCart::where('user_id', $userId)
            ->where('product_id', $productId)
            ->first();

        if ($cartItem) {
            // 更新数量
            $newQuantity = $cartItem->quantity + $quantity;
            if ($newQuantity > $product->stock) {
                return response()->json([
                    'success' => false,
                    'message' => '库存不足'
                ]);
            }
            $cartItem->update(['quantity' => $newQuantity]);
        } else {
            // 创建新的购物车项
            SimpleCart::create([
                'user_id' => $userId,
                'product_id' => $productId,
                'quantity' => $quantity
            ]);
        }

        // 获取购物车总数量
        $totalQuantity = SimpleCart::where('user_id', $userId)->sum('quantity');

        return response()->json([
            'success' => true,
            'message' => '已添加到购物车',
            'total_quantity' => $totalQuantity
        ]);
    }

    /**
     * 更新购物车商品数量
     */
    public function update(Request $request)
    {
        // 检查用户是否已登录
        if (!auth('wechat')->check()) {
            return response()->json([
                'success' => false,
                'message' => '请先登录'
            ], 401);
        }

        $request->validate([
            'cart_item_id' => 'required|exists:simple_carts,id',
            'quantity' => 'required|integer|min:1',
        ]);

        $cartItemId = $request->input('cart_item_id');
        $quantity = (int)$request->input('quantity');
        $userId = auth('wechat')->id();

        $cartItem = SimpleCart::where('id', $cartItemId)
            ->where('user_id', $userId)
            ->with('product')
            ->first();

        if (!$cartItem) {
            return response()->json([
                'success' => false,
                'message' => '购物车项不存在'
            ]);
        }

        if ($quantity > $cartItem->product->stock) {
            return response()->json([
                'success' => false,
                'message' => '库存不足'
            ]);
        }

        $cartItem->update(['quantity' => $quantity]);

        return response()->json([
            'success' => true,
            'message' => '购物车已更新'
        ]);
    }

    /**
     * 移除购物车中的商品
     */
    public function remove(Request $request)
    {
        // 检查用户是否已登录
        if (!auth('wechat')->check()) {
            return response()->json([
                'success' => false,
                'message' => '请先登录'
            ], 401);
        }

        $request->validate([
            'cart_item_id' => 'required|exists:simple_carts,id',
        ]);

        $cartItemId = $request->input('cart_item_id');
        $userId = auth('wechat')->id();

        $cartItem = SimpleCart::where('id', $cartItemId)
            ->where('user_id', $userId)
            ->first();

        if ($cartItem) {
            $cartItem->delete();
        }

        return response()->json([
            'success' => true,
            'message' => '已移除商品'
        ]);
    }
    
    /**
     * 清空购物车
     */
    public function empty(Request $request)
    {
        // 检查用户是否已登录
        if (!auth('wechat')->check()) {
            return response()->json([
                'success' => false,
                'message' => '请先登录'
            ], 401);
        }

        $userId = auth('wechat')->id();
        
        // 删除用户的所有购物车商品
        SimpleCart::where('user_id', $userId)->delete();

        return response()->json([
            'success' => true,
            'message' => '购物车已清空'
        ]);
    }

    /**
     * 清空购物车
     */
    public function clear()
    {
        // 检查用户是否已登录
        if (!auth('wechat')->check()) {
            return response()->json([
                'success' => false,
                'message' => '请先登录'
            ], 401);
        }

        $userId = auth('wechat')->id();
        SimpleCart::where('user_id', $userId)->delete();

        return response()->json([
            'success' => true,
            'message' => '购物车已清空'
        ]);
    }
}
